<template>
  <div class="alert-rules">
    <!-- 添加/编辑规则对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加告警规则' : '编辑告警规则'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="ruleForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="规则类型" prop="rule_type">
          <el-select v-model="ruleForm.rule_type" placeholder="请选择规则类型" style="width: 100%">
            <el-option label="数据量异常" value="DATA_VOLUME_ANOMALY" />
            <el-option label="增长率异常" value="GROWTH_RATE_ANOMALY" />
            <el-option label="空表检测" value="EMPTY_TABLE_DETECTION" />
            <el-option label="重复数据检测" value="DUPLICATE_DATA_DETECTION" />
            <el-option label="数据延迟检测" value="DATA_DELAY_DETECTION" />
          </el-select>
        </el-form-item>
        <el-form-item label="告警级别" prop="severity">
          <el-select v-model="ruleForm.severity" placeholder="请选择告警级别" style="width: 100%">
            <el-option label="低" value="LOW" />
            <el-option label="中" value="MEDIUM" />
            <el-option label="高" value="HIGH" />
            <el-option label="严重" value="CRITICAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标表" prop="target_tables">
          <el-select
            v-model="ruleForm.target_tables"
            multiple
            placeholder="请选择要监控的表"
            style="width: 100%"
          >
            <el-option
              v-for="table in tables"
              :key="table.id"
              :label="`${table.table_name} (${table.layer})`"
              :value="table.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="阈值配置" prop="threshold_config">
          <el-input
            v-model="ruleForm.threshold_config"
            type="textarea"
            :rows="3"
            placeholder="请输入阈值配置JSON"
          />
        </el-form-item>
        <el-form-item label="通知方式" prop="notification_methods">
          <el-checkbox-group v-model="ruleForm.notification_methods">
            <el-checkbox label="email">邮件</el-checkbox>
            <el-checkbox label="wechat">企业微信</el-checkbox>
            <el-checkbox label="sms">短信</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="ruleForm.is_active" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="ruleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入规则描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>告警规则管理</span>
        </div>
      </template>

      <!-- 数据量统计 -->
      <div class="data-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-primary">
              <div class="stat-item">
                <div class="stat-value">{{ ruleStats.total }}</div>
                <div class="stat-label">总规则数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-success">
              <div class="stat-item">
                <div class="stat-value">{{ ruleStats.active }}</div>
                <div class="stat-label">启用规则</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-warning">
              <div class="stat-item">
                <div class="stat-value">{{ ruleStats.inactive }}</div>
                <div class="stat-label">禁用规则</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-danger">
              <div class="stat-item">
                <div class="stat-value">{{ ruleStats.critical }}</div>
                <div class="stat-label">严重规则</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索和筛选 -->
      <div class="filter-section card-section">
        <div class="section-header">
          <h3 class="section-title">筛选条件</h3>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="filters.search"
              placeholder="搜索规则名称或描述"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.ruleType" placeholder="规则类型" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="数据量异常" value="data_volume" />
              <el-option label="自定义规则" value="custom" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.severity" placeholder="严重程度" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
              <el-option label="严重" value="critical" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.status" placeholder="状态" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="启用" value="true" />
              <el-option label="禁用" value="false" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleFilter">筛选</el-button>
            <el-button @click="clearFilters">清除</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 表格工具栏 -->
      <div class="table-toolbar card-section">
        <div class="section-header">
          <h3 class="section-title">操作工具栏</h3>
        </div>
        <div class="toolbar-content">
          <div class="left">
            <el-button type="success" size="small" @click="handleBatchEnable">批量启用</el-button>
            <el-button type="warning" size="small" @click="handleBatchDisable">批量禁用</el-button>
          </div>
          <div class="right">
            <el-button type="primary" size="small" @click="showAddDialog">添加规则</el-button>
            <el-button size="small" @click="refreshRules">刷新</el-button>
            <el-dropdown @command="handleColumnToggle">
              <el-button size="small">
                列设置 <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item 
                    v-for="col in availableColumns" 
                    :key="col.prop"
                    :command="col.prop"
                  >
                    <el-checkbox 
                      v-model="col.visible" 
                      @change="toggleColumn(col.prop)"
                    >
                      {{ col.label }}
                    </el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
      
      <el-card class="table-card">
        <template #header>
          <div class="section-header">
            <h3 class="section-title">规则列表</h3>
          </div>
        </template>
        <el-table :data="filteredRules" style="width: 100%" v-loading="loading">
          <el-table-column prop="name" label="规则名称" />
          <el-table-column prop="rule_type" label="规则类型">
            <template #default="{ row }">
              <el-tag size="small">{{ getRuleTypeText(row.rule_type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="severity" label="告警级别">
            <template #default="{ row }">
              <el-tag :type="getSeverityType(row.severity)" size="small">
                {{ getSeverityText(row.severity) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="is_active" label="状态">
            <template #default="{ row }">
              <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
                {{ row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="editRule(row)">编辑</el-button>
              <el-button type="text" size="small" @click="toggleRule(row)">
                {{ row.is_active ? '禁用' : '启用' }}
              </el-button>
              <el-button type="text" size="small" @click="deleteRule(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { alertApi } from '@/api/alert'
import { monitorApi } from '@/api/monitor'
import type { AlertRule, MonitoredTable } from '@/types'
import { Search, ArrowDown } from '@element-plus/icons-vue'

// 响应式数据
const rules = ref<AlertRule[]>([])
const tables = ref<MonitoredTable[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()

// 筛选条件
const filters = reactive({
  search: '',
  ruleType: '',
  severity: '',
  status: ''
})

// 列设置
const availableColumns = ref([
  { prop: 'name', label: '规则名称', visible: true },
  { prop: 'rule_type', label: '规则类型', visible: true },
  { prop: 'severity', label: '严重程度', visible: true },
  { prop: 'is_active', label: '状态', visible: true },
  { prop: 'created_at', label: '创建时间', visible: true }
])

// 规则统计
const ruleStats = computed(() => {
  const stats = {
    total: rules.value.length,
    active: rules.value.filter(rule => rule.is_active).length,
    inactive: rules.value.filter(rule => !rule.is_active).length,
    critical: rules.value.filter(rule => rule.severity === 'CRITICAL').length
  }
  return stats
})

// 筛选后的规则数据
const filteredRules = computed(() => {
  let result = rules.value
  
  if (filters.search) {
    const searchLower = filters.search.toLowerCase()
    result = result.filter(rule => 
      rule.name?.toLowerCase().includes(searchLower) ||
      rule.description?.toLowerCase().includes(searchLower)
    )
  }
  
  if (filters.ruleType) {
    result = result.filter(rule => rule.rule_type === filters.ruleType)
  }
  
  if (filters.severity) {
    result = result.filter(rule => rule.severity === filters.severity)
  }
  
  if (filters.status !== '') {
    const statusBool = filters.status === 'true'
    result = result.filter(rule => rule.is_active === statusBool)
  }
  
  return result
})

// 表单数据
const ruleForm = ref<{
  id?: number
  name: string
  rule_type: any
  severity: any
  target_tables: number[]
  threshold_config: string
  notification_methods: string[]
  is_active: boolean
  description: string
}>({
  name: '',
  rule_type: '' as any,
  severity: 'MEDIUM' as any,
  target_tables: [],
  threshold_config: '',
  notification_methods: [],
  is_active: true,
  description: ''
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  rule_type: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  severity: [
    { required: true, message: '请选择告警级别', trigger: 'change' }
  ],
  target_tables: [
    { required: true, message: '请选择监控的表', trigger: 'change' }
  ]
}

const loadRules = async () => {
  loading.value = true
  try {
    const response = await alertApi.getRules()
    rules.value = response.data
  } catch (error) {
    console.error('Failed to load rules:', error)
    ElMessage.error('加载告警规则失败')
  } finally {
    loading.value = false
  }
}

const loadTables = async () => {
  try {
    const response = await monitorApi.getTables({ page: 1, size: 100 })
    tables.value = response.data.items
  } catch (error) {
    console.error('Failed to load tables:', error)
  }
}

const showAddDialog = () => {
  dialogType.value = 'add'
  ruleForm.value = {
    name: '',
    rule_type: '',
    severity: 'MEDIUM',
    target_tables: [],
    threshold_config: '',
    notification_methods: [],
    is_active: true,
    description: ''
  }
  dialogVisible.value = true
}

const editRule = (rule: AlertRule) => {
  dialogType.value = 'edit'
  ruleForm.value = { 
    id: rule.id,
    name: rule.name,
    rule_type: rule.rule_type,
    severity: rule.severity,
    target_tables: [], // AlertRule接口中没有这个属性
    threshold_config: JSON.stringify(rule.conditions, null, 2),
    notification_methods: [], // AlertRule接口中没有这个属性
    is_active: rule.is_active,
    description: rule.description || ''
  }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await alertApi.createRule(ruleForm.value)
      ElMessage.success('添加成功')
    } else {
      await alertApi.updateRule(ruleForm.value.id!, ruleForm.value)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    loadRules()
  } catch (error) {
    console.error('Form submission failed:', error)
    ElMessage.error('操作失败')
  }
}

const toggleRule = async (rule: AlertRule) => {
  try {
    await alertApi.toggleRule(rule.id, !rule.is_active)
    ElMessage.success(rule.is_active ? '禁用成功' : '启用成功')
    loadRules()
  } catch (error) {
    console.error('Toggle rule failed:', error)
    ElMessage.error('操作失败')
  }
}

const deleteRule = async (rule: AlertRule) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除规则 "${rule.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await alertApi.deleteRule(rule.id)
    ElMessage.success('删除成功')
    loadRules()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete failed:', error)
      ElMessage.error('删除失败')
    }
  }
}

const getRuleTypeText = (type: string): string => {
  const texts: Record<string, string> = {
    'DATA_VOLUME_ANOMALY': '数据量异常',
    'GROWTH_RATE_ANOMALY': '增长率异常',
    'EMPTY_TABLE_DETECTION': '空表检测',
    'DUPLICATE_DATA_DETECTION': '重复数据检测',
    'DATA_DELAY_DETECTION': '数据延迟检测'
  }
  return texts[type] || type
}

const getSeverityType = (severity: string): string => {
  const types: Record<string, string> = {
    'LOW': 'info',
    'MEDIUM': 'warning',
    'HIGH': 'danger',
    'CRITICAL': 'danger'
  }
  return types[severity] || 'info'
}

const getSeverityText = (severity: string): string => {
  const texts: Record<string, string> = {
    'LOW': '低',
    'MEDIUM': '中',
    'HIGH': '高',
    'CRITICAL': '严重'
  }
  return texts[severity] || severity
}

const formatTime = (time: string): string => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  // 实时搜索，不需要额外处理
}

// 筛选处理
const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

// 清除筛选
const clearFilters = () => {
  filters.search = ''
  filters.ruleType = ''
  filters.severity = ''
  filters.status = ''
}

// 批量启用
const handleBatchEnable = () => {
  ElMessage.info('批量启用功能开发中...')
}

// 批量禁用
const handleBatchDisable = () => {
  ElMessage.info('批量禁用功能开发中...')
}

// 刷新规则
const refreshRules = () => {
  loadRules()
}

// 列设置
const handleColumnToggle = (prop: string) => {
  // 列切换逻辑
}

const toggleColumn = (prop: string) => {
  // 切换列显示/隐藏
}

// 获取列显示状态
const getColumnVisible = (prop: string): boolean => {
  const column = availableColumns.value.find(col => col.prop === prop)
  return column ? column.visible : true
}

onMounted(() => {
  loadRules()
  loadTables()
})
</script>

<style scoped>
.alert-rules { padding: 0; }
.page-card { background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); }
.card-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 6px; border-bottom: 1px dashed #eef2f6; }

.data-stats { margin-bottom: 20px; }
.stat-card { text-align: center; border-left: 4px solid var(--accent, #409EFF); background: linear-gradient(180deg, var(--accent-bg, #f0f7ff) 0%, #ffffff 40%); }
.stat-card.accent-primary { --accent:#409eff; --accent-bg:#f0f7ff; }
.stat-card.accent-success { --accent:#67C23A; --accent-bg:#ecfdf5; }
.stat-card.accent-warning { --accent:#E6A23C; --accent-bg:#fdf6ec; }
.stat-card.accent-danger { --accent:#F56C6C; --accent-bg:#feecec; }
.stat-item { padding: 20px; }
.stat-value { font-size: 24px; font-weight: 800; margin-bottom: 8px; color: var(--accent, #409EFF); }
.stat-label { color: #606266; font-size: var(--font-subtitle); }

.card-section { background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); padding: 16px; margin-bottom: 16px; }
.section-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 6px; margin-bottom: 8px; border-bottom: 1px dashed #eef2f6; }
.section-title { margin: 0; font-size: var(--font-title); font-weight: 700; color: #1f2937; }

.table-toolbar { margin-bottom: 16px; }
.toolbar-content { display: flex; justify-content: space-between; align-items: center; }

.table-card { margin-top: 8px; background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); }

.dialog-footer { display: flex; justify-content: flex-end; gap: 10px; }
</style> 